package hu.codelab.lg.servicecenter.activity;

import hu.codelab.lg.servicecenter.R;
import hu.codelab.lg.servicecenter.ServiceCenterApplication;
import hu.codelab.lg.servicecenter.activity.Eula.OnEulaAgreedTo;
import hu.codelab.lg.servicecenter.widget.LGDialog;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Region;
import android.graphics.Typeface;
import android.os.AsyncTask;
import android.os.AsyncTask.Status;
import android.os.Bundle;
import android.text.Html;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.style.RelativeSizeSpan;
import android.text.style.StyleSpan;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends BaseActivity implements OnEulaAgreedTo {
    
    private static final int DIALOG_REFESH = 0;
    private static final int DIALOG_INFOS = 1;
    private static final int DIALOG_ABOUT = 2;
    private static final int DIALOG_NO_CONNECTION = 3;
    
    private static final String FILENAME = "service_list.xml";
    private static final String REFRESH_URL = "http://www.lg.com/hu/mobil/cr_mobil_app_list.xml";
    
    private RelativeLayout layout;
    private Typeface font;
    
    protected RefreshTask refreshTask;
    
    protected class RefreshTask extends AsyncTask<Void, Void, Void> {
        
        @Override
        protected Void doInBackground(Void... params) {
            MainActivity.this.refreshDatabase();
            return null;
        }
        
        @Override
        protected void onPostExecute(final Void result) {
            MainActivity.this.removeDialog(DIALOG_REFESH);
            Toast.makeText(MainActivity.this, "Adatbázis frissítve.", Toast.LENGTH_LONG).show();
        }
        
        @Override
        protected void onPreExecute() {
            MainActivity.this.showDialog(DIALOG_REFESH);
        }
    }
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        
        super.onCreate(savedInstanceState);
        
        final Resources resources = getResources();
        font = Typeface.createFromAsset(getAssets(), "helvetica_neue.ttf");
        
        layout = (RelativeLayout) getLayoutInflater().inflate(R.layout.activity_main, null);
        setContentView(layout);
        
        final Button buttonList = (Button) layout.findViewById(R.id.b_main_list);
        final Button buttonMap = (Button) layout.findViewById(R.id.b_main_map);
        final Button buttonInfo = (Button) layout.findViewById(R.id.b_main_info);
        final TextView textviewTitle = (TextView) layout.findViewById(R.id.tv_main_title);
        final TextView textviewFooter = (TextView) layout.findViewById(R.id.tv_main_footer);
        
        buttonList.setTypeface(font);
        buttonMap.setTypeface(font);
        buttonInfo.setTypeface(font);
        textviewTitle.setTypeface(font);
        textviewFooter.setTypeface(font);
        
        SpannableString title = new SpannableString(resources.getString(R.string.main_button_info));
        title.setSpan(new StyleSpan(Typeface.BOLD), 0, title.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        buttonInfo.setText(title);
        
        SpannableStringBuilder builder = new SpannableStringBuilder();
        title = new SpannableString(resources.getString(R.string.main_button_list));
        title.setSpan(new StyleSpan(Typeface.BOLD), 0, title.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        SpannableString description = new SpannableString(resources.getString(R.string.main_button_list_desc));
        description.setSpan(new RelativeSizeSpan(0.8f), 0, description.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        builder.append(title).append('\n').append(description);
        buttonList.setText(builder);
        
        builder = new SpannableStringBuilder();
        title = new SpannableString(resources.getString(R.string.main_button_map));
        title.setSpan(new StyleSpan(Typeface.BOLD), 0, title.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        description = new SpannableString(resources.getString(R.string.main_button_map_desc));
        description.setSpan(new RelativeSizeSpan(0.8f), 0, description.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        builder.append(title).append('\n').append(description);
        buttonMap.setText(builder);
        
        buttonList.setOnClickListener(new View.OnClickListener() {
            
            @Override
            public void onClick(final View view) {
                startActivity(new Intent(getBaseContext(), ListActivity.class));
            }
            
        });
        
        buttonMap.setOnClickListener(new View.OnClickListener() {
            
            @Override
            public void onClick(final View view) {
                if (ServiceCenterApplication.isNetworkAvailable(getBaseContext())) {
                    startActivity(new Intent(getBaseContext(), LGMapActivity.class));
                } else {
                    showDialog(DIALOG_NO_CONNECTION);
                }
            }
            
        });
        
        buttonInfo.setOnClickListener(new View.OnClickListener() {
            
            @Override
            public void onClick(final View view) {
                showDialog(DIALOG_INFOS);
            }
            
        });
        
        if (Eula.show(MainActivity.this)) {
            layout.setVisibility(View.VISIBLE);
        }
    }
    
    @Override
    protected void onResume() {
        ((ServiceCenterApplication) getApplication()).setCurrentServiceCenter(null);
        super.onResume();
    }
    
    @Override
    public void onEulaAgreedTo() {
        layout.setVisibility(View.VISIBLE);
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu, menu);
        return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.mi_refresh:
                refreshTask = new RefreshTask();
                refreshTask.execute();
                MainActivity.this.showDialog(DIALOG_REFESH);
                break;
            case R.id.mi_about:
                MainActivity.this.showDialog(DIALOG_ABOUT);
                break;
            default:
                break;
        }
        return super.onOptionsItemSelected(item);
    }
    
    @Override
    protected Dialog onCreateDialog(final int id) {
        Dialog dialog = null;
        
        switch (id) {
            case DIALOG_INFOS:
                dialog = new LGDialog(MainActivity.this, R.style.Theme_Dialog_Translucent);
                dialog.setContentView(R.layout.dialog_infos);
                TextView lorem = (TextView) dialog.findViewById(R.id.tv_dialog_infos_lorem);
                TextView title = (TextView) dialog.findViewById(R.id.tv_dialog_infos_title);
                ImageButton close = (ImageButton) dialog.findViewById(R.id.ib_dialog_infos_close);
                
                lorem.setTypeface(font);
                title.setTypeface(font);
                title.setText("Mit vigyek magammal?");
                
                String myHtmlString = "&#8226; Hiánytalanul kitöltött és az értékesítő által lepecsételt, érvényes garanciajegy<br/><br/> &#8226; A vásárlást igazoló számla<br/><br/>&#8226; A meghibásodott termék és annak tartozékai";
                
                lorem.setText(Html.fromHtml(myHtmlString));
                
                close.setOnClickListener(new View.OnClickListener() {
                    
                    @Override
                    public void onClick(final View view) {
                        removeDialog(DIALOG_INFOS);
                    }
                    
                });
                
                dialog.setCanceledOnTouchOutside(true);
                break;
            case DIALOG_REFESH:
                dialog = ProgressDialog.show(MainActivity.this, "", "Adatok betöltése folyamatban...", true);
                dialog.setCancelable(true);
                dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
                    
                    @Override
                    public void onCancel(DialogInterface dlg) {
                        if (refreshTask != null && refreshTask.getStatus() == Status.RUNNING) {
                            refreshTask.cancel(true);
                        }
                    }
                });
                
                break;
            case DIALOG_ABOUT:
                dialog = new LGDialog(MainActivity.this, R.style.Theme_Dialog_Translucent);
                dialog.setContentView(R.layout.dialog_infos);
                lorem = (TextView) dialog.findViewById(R.id.tv_dialog_infos_lorem);
                title = (TextView) dialog.findViewById(R.id.tv_dialog_infos_title);
                close = (ImageButton) dialog.findViewById(R.id.ib_dialog_infos_close);
                
                lorem.setTypeface(font);
                title.setTypeface(font);
                title.setText("Információk");
                
                String htmlString = "&#169;2011 LG<br/>Az alkalmazásban előforduló szövegi és képi elemek az LG Electronics tulajdonát képezik. Minden jog fenntartva!<br/><br/>Fejlesztők:<br/>info@codelab.hu";
                
                lorem.setText(Html.fromHtml(htmlString));
                close.setOnClickListener(new View.OnClickListener() {
                    
                    @Override
                    public void onClick(final View view) {
                        removeDialog(DIALOG_ABOUT);
                    }
                    
                });
                
                break;
            case DIALOG_NO_CONNECTION:
                dialog = new LGDialog(MainActivity.this, R.style.Theme_Dialog_Translucent);
                dialog.setContentView(R.layout.dialog_infos);
                lorem = (TextView) dialog.findViewById(R.id.tv_dialog_infos_lorem);
                title = (TextView) dialog.findViewById(R.id.tv_dialog_infos_title);
                close = (ImageButton) dialog.findViewById(R.id.ib_dialog_infos_close);
                
                lorem.setTypeface(font);
                title.setTypeface(font);
                title.setText("Hálózat nem elérhető");
                
                close.setOnClickListener(new View.OnClickListener() {
                    
                    @Override
                    public void onClick(final View view) {
                        removeDialog(DIALOG_NO_CONNECTION);
                    }
                    
                });
                
                dialog.setCanceledOnTouchOutside(true);
                break;
            default:
                break;
        }
        
        if (dialog != null && dialog instanceof LGDialog) {
            final RelativeLayout dialogLayout = (RelativeLayout) dialog.findViewById(R.id.rl_dialog);
            
            ((LGDialog) dialog).setOnTouchEventListener(new LGDialog.OnTouchEventListener() {
                
                @Override
                public void onTouchEvent(final Dialog diag, final MotionEvent event) {
                    final Region dialogRegion = new Region(dialogLayout.getLeft(), dialogLayout.getTop(), dialogLayout.getRight(), dialogLayout.getBottom());
                    
                    if (dialogRegion.contains((int) event.getX(), (int) event.getY())) {
                        return;
                    }
                    
                    diag.dismiss();
                }
                
            });
        }
        
        return dialog;
    }
    
    protected void refreshDatabase() {
        FileOutputStream fos;
        try {
            fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
            new DefaultHttpClient().execute(new HttpGet(REFRESH_URL)).getEntity().writeTo(fos);
            ((ServiceCenterApplication) getApplication()).refreshServiceCenterList();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
}
